<template>
  <div>
    <el-form class="query-form" :inline="true" :model="params">
      <el-form-item>
        <el-input v-model="params.load_name" placeholder="产品名称查询"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getData()" icon="el-icon-search">查询</el-button>
      </el-form-item>
      <el-form-item class="float-right">
        <el-button type="primary" @click="handleEditProduct()" icon="el-icon-plus" v-show="isSuper">
          新增
        </el-button>
      </el-form-item>
    </el-form>

    <c-table
      border
      v-loading="loading"
      :stripe="false"
      :columns="tableColumns"
      :data="tableData"
      :row-class-name="goodsRowClass"
    >
      <template v-slot:loadName="scope">
        <div>{{ scope.row.load_name }}</div>
        <small v-if="+scope.row.shelves_status === 2" class="text-warning">（产品已下架）</small>
      </template>
    </c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <goods-view-dialog :visible.sync="viewFormVisible" :goods-id="viewFormId"></goods-view-dialog>

    <goods-edit-dialog
      :visible.sync="editFormVisible"
      :form-data="editFormData"
      :table-id="editTableId"
      @success="getData(params.index)"
    ></goods-edit-dialog>

    <!-- <goods-cond-edit-dialog
      :visible.sync="condFormVisible"
      :goods-id="condTableId"
      @success="getData(params.index)"
    ></goods-cond-edit-dialog> -->

    <!-- <risk-cond-edit-dialog
      :visible.sync="riskVisible"
      :goods-id="riskCondId"
      @success="getData(params.index)"
    ></risk-cond-edit-dialog> -->

    <goods-credit-dialog
      :visible.sync="creditVisible"
      :form-data="creditData"
      @success="getData(params.index)"
    ></goods-credit-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getParams } from '@/credit/views/province/goods/goodsMixins'

import GoodsViewDialog from '@/credit/views/province/goods/GoodsViewDialog'
import GoodsEditDialog from '@/credit/views/province/goods/GoodsEditDialog'
// import GoodsCondEditDialog from '@/credit/views/province/goods/GoodsCondEditDialog'
// import RiskCondEditDialog from '@/credit/views/province/goods/RiskCondEditDialog'
import GoodsCreditDialog from '@/credit/views/province/goods/GoodsCreditDialog'

export default {
  components: {
    GoodsViewDialog,
    GoodsEditDialog,
    // GoodsCondEditDialog,
    // RiskCondEditDialog,
    GoodsCreditDialog,
  },
  props: {},
  data() {
    return {
      loading: false,
      params: {
        index: 1,
        size: 10,
        load_name: '',
        'is_guarantee.eq': '0',
      },
      tableName: 'industrial_package',
      totalCount: 0,
      tableData: [],
      tableColumns: [
        { attrs: { label: '产品名', prop: 'load_name', minWidth: 120 }, slot: 'loadName' },
        { attrs: { label: '创建时间', prop: 'create_time', width: 100 } },
        { attrs: { label: '支持产业', prop: 'supply_product_name', minWidth: 100 } },
        { attrs: { label: '适用区域', prop: 'supply_address_code_name', minWidth: 120 } },
        { attrs: { label: '适用对象', prop: 'load_entity', minWidth: 130 } },
        { attrs: { label: '担保额度(万元)', prop: 'fundsRang' } },
        { attrs: { label: '融资期限(月)', prop: 'yearRang' } },
        { attrs: { label: '担保费率', prop: 'gua_rate' } },
        { attrs: { label: '贷款利率', prop: 'bank_rate' } },
        {
          attrs: { label: '操作', align: 'center', width: 150, fixed: 'right' },
          operations: [
            // {
            //   content: '审核',
            //   icon: 'fa fa-gavel',
            //   event: this.handleApproval,
            //   ifRender: row =>
            //     this.isSuper && row.is_approval === 0 && row.service_id === this.clientId,
            // },
            {
              content: '编辑产品信息',
              icon: 'fa fa-edit',
              event: this.handleEditProduct,
              ifRender: row => this.isSuper && row.service_id === this.clientId,
            },
            // {
            //   content: '编辑准入条件',
            //   icon: 'fa fa-check-square-o',
            //   event: this.handleEditCondition,
            //   ifRender: row => this.isSuper && row.service_id === this.clientId,
            // },
            // {
            //   content: '编辑分险措施',
            //   icon: 'fa fa-exclamation-triangle',
            //   event: this.handleEditRisk,
            //   ifRender: row => this.isSuper && row.service_id === this.clientId,
            // },
            {
              content: '编辑融资方案',
              icon: 'fa fa-jpy',
              event: this.handleEditCredit,
              ifRender: row => this.isSuper && row.service_id === this.clientId,
            },
            {
              content: row => (+row.shelves_status === 1 ? '下架' : '上架'),
              icon: 'fa fa-exchange transform-90deg',
              event: this.handleShelf,
              ifRender: row => this.isSuper && row.service_id === this.clientId,
            },
            {
              content: '删除',
              icon: 'fa fa-trash',
              event: this.handleDelete,
              attrs: { class: 'text-danger py-0 px-2' },
              ifRender: row => this.isSuper && row.service_id === this.clientId,
            },
            {
              content: '查看',
              icon: 'fa fa-search',
              event: this.handleView,
            },
          ],
        },
      ],

      editFormVisible: false,
      editTableId: '',
      editFormData: {},

      condFormVisible: false,
      condTableId: '',

      viewFormVisible: false,
      viewFormId: '',

      riskVisible: false,
      riskCondId: '',

      creditVisible: false,
      creditData: {},
    }
  },
  computed: {
    ...mapGetters(['user', 'org', 'job', 'clientId']),
    isUserProvince() {
      return this.user.orgRegionLever === 1
    },
    isUserCity() {
      return this.user.orgRegionLever === 2
    },
    isSuper() {
      return this.user.scopeArr.includes('agencyM')
    },
  },
  watch: {},
  created() {
    this.params = {
      ...this.params,
      ...getParams(this.user, this.org),
    }

    this.getData()
  },
  mounted() {},
  methods: {
    // handleEditRisk(row = {}) {
    //   this.riskVisible = true
    //   this.riskCondId = row.industrial_package_id
    // },
    async getData(index = 1) {
      this.params.index = index

      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, this.params)
      )
      this.loading = false

      const data = (res && res.data) || {}
      this.tableData = (data.data || []).map(this.dataAdapter)
      this.totalCount = data.totalCount || 0
    },
    dataAdapter(item) {
      item.fundsRang = `${item.load_amount_min || ''}~${item.load_amount || ''}`
      item.yearRang = `${item.loan_term_min || ''}~${item.loan_term || ''}`
      return item
    },
    goodsRowClass({ row }) {
      const isOnShelf = +row.shelves_status === 1
      return isOnShelf ? '' : 'off-shelf'
    },
    handleView(row = {}) {
      this.viewFormId = row?.industrial_package_id ?? ''
      this.viewFormVisible = true
    },
    handleEditProduct(row = {}) {
      this.editFormData = { ...row }
      this.editTableId = row.industrial_package_id
      this.editFormVisible = !this.editFormVisible
    },
    // handleEditCondition(row = {}) {
    //   this.condTableId = row.industrial_package_id
    //   this.condFormVisible = true
    // },
    handleEditCredit(row = {}) {
      this.creditData = { ...row }
      this.creditVisible = true
    },
    // handleApproval(row) {
    //   this.$utils
    //     .msgbox({
    //       message: `确定审批通过?`,
    //       type: 'warning',
    //       title: '审批产品',
    //       beforeClose: () =>
    //         this.$api.updateData(this.$serviceName, this.tableName, row.industrial_package_id, {
    //           is_approval: 1,
    //         }),
    //     })
    //     .then(() => {
    //       this.$message.success('审批成功！')
    //       this.getData()
    //     })
    //     .catch(() => this.$message.error('审批失败，请重试！'))
    // },
    handleShelf(row) {
      const isOnShelf = +row.shelves_status === 1
      const shelfLabel = isOnShelf ? '下架' : '上架'
      this.$utils
        .msgbox({
          message: `确定${shelfLabel}产品 ${row.load_name || ''}?`,
          type: 'warning',
          beforeClose: () =>
            this.$api.updateData(this.$serviceName, this.tableName, row.industrial_package_id, {
              shelves_status: isOnShelf ? 2 : 1,
            }),
        })
        .then(() => {
          this.$message.success(`${shelfLabel}成功！`)
          this.getData()
        })
        .catch(() => this.$message.error(`${shelfLabel}失败，请重试！`))
    },
    async handleDelete(row) {
      this.$utils
        .msgbox({
          message: `确定删除 ${row.load_name || ''}? 若有项目使用过请谨慎删除！`,
          type: 'warning',
          beforeClose: () =>
            this.$api.deleteData(this.$serviceName, this.tableName, row.industrial_package_id),
        })
        .then(() => {
          this.$message.success('删除成功！')
          this.getData()
        })
        .catch(() => this.$message.error('删除失败，请重试！'))
    },
  },
}
</script>
<style lang="scss" scoped>
/deep/ .off-shelf {
  background-color: #fdf6ec;
  border-color: #faecd8;
  color: #e6a23c;
}
/deep/ .transform-90deg {
  transform: rotate(90deg);
}
</style>
